﻿namespace HuaWei
{
    using System;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Text;

    public class IniFile
    {
        public static void DeleteKey(string Section, string Ident, string filePath)
        {
            WritePrivateProfileString(Section, Ident, null, filePath);
        }

        public static void EraseSection(string Section, string filePath)
        {
            if (WritePrivateProfileString(Section, null, null, filePath) == 0L)
            {
                throw new ApplicationException("无法清除Ini文件中的Section");
            }
        }

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string str, string str1, string str2, StringBuilder strBuilder, int num, string str3);
        public static string ReadIniFile(string filename, string section, string key)
        {
            return ReadIniFile(filename, section, key, true);
        }

        public static string ReadIniFile(string filename, string section, string key, bool isEncrypted)
        {
            FileInfo info = new FileInfo(filename);
            int length = (int) info.Length;
            StringBuilder strBuilder = new StringBuilder(length);
            GetPrivateProfileString(section, key, "", strBuilder, length, filename);
            string pToDecrypt = strBuilder.ToString().Trim();
            if (isEncrypted)
            {
                pToDecrypt = EncryptDecrypt.Decrypt(pToDecrypt, EncryptDecrypt.EncryptionType.DES);
            }
            return pToDecrypt;
        }

        public static void WriteIniFile(string filename, string section, string key, string keyValue)
        {
            WriteIniFile(filename, section, key, keyValue, true);
        }

        public static void WriteIniFile(string filename, string section, string key, string keyValue, bool isEncrypted)
        {
            if (isEncrypted)
            {
                keyValue = EncryptDecrypt.Encrypt(keyValue, EncryptDecrypt.EncryptionType.DES);
            }
            WritePrivateProfileString(section, key, keyValue, filename);
        }

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string str, string str1, string str2, string str3);
    }
}

